# -*- coding: utf-8 -*-
# !/usr/bin/env python
# !/usr/bin/python3
# @Time    : 2021/3/17 18:33
# @Author  : buke-freedom
# @File    : bs4数据解析基础.py
"""
# @description：
https://www.shicimingju.com/book/sanguoyanyi.html
爬取三国演义所有章节的标题和章节内容
"""
import requests
from bs4 import BeautifulSoup
import lxml

if __name__ == "__main__":
    # 对首页的页面数据进行爬取
    url = 'https://www.shicimingju.com/book/sanguoyanyi.html'
    # UA伪装：将对应的User_Agent封装到一个字典中
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0"
    }
    page_text = requests.get(url=url, headers=headers).text
    # 在首页中解析出章节的标题和详情页url
    # 实例化BeautifulSoup对象，需要将页面数据加载到该对象中
    soup = BeautifulSoup(page_text, 'lxml')
    # 解析章节标题和详情页url
    li_list = soup.select('.book-mulu > ul >li')
    fp = open('./sanguo.txt', 'w', encoding='utf-8')
    for li in li_list:
        title = li.a.string

        detail_url = 'https://www.shicimingju.com' + li.a['href']
        # d对详情页发起请求，获取章节详细内容
        detail_page_text = requests.get(url=detail_url, headers=headers).text.encode('iso-8859-1')
        # 解析出详情页中的相关章节内容
        detail_soup = BeautifulSoup(detail_page_text, 'lxml')
        div_tag = detail_soup.find('div', class_='chapter_content')
        # 解析到了章节的内容
        content = div_tag.text
        # 三国演义网站出现乱码需要在response读取.text后面加上.encode('iso-8859-1')
        fp.write(title + ':' + content + '\n')
        #print(title, "爬取成功！")
